import java.util.Stack;

public class ReverseListS {
    public static class ListNode{
        int val;
        ListNode next;
        ListNode(){}
        ListNode(int val){
            this.val = val;
        }
    }

    //使用栈方法的最大难点是：从栈中取出节点的顺序可不代表他们的物理顺序
    //试试——入栈的时候就清除节点之间的联系
    public ListNode reverseList(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
            //将每个节点解除联系之后放入栈中
        while (head != null){
            stack.push(head);
            head = head.next;
        }
        if(stack.isEmpty()){
            return null;
        }
        //将节点从栈中取出
        ListNode newhead = stack.pop();
        ListNode cur = newhead;
        while (!stack.isEmpty()){
            ListNode next = stack.pop();
            cur.next = next;
            cur = cur.next;
        }
        cur.next = null;
        return newhead;
    }


    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(12);
        ListNode listNode2 = new ListNode(26);
        ListNode listNode3 = new ListNode(45);
        ListNode listNode4 = new ListNode(180);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        ReverseListS r = new ReverseListS();
        ListNode Head = r.reverseList(listNode1);
        System.out.println(Head.val);
    }
}
